import React, {Component, createContext, useContext} from 'react';
import './index.css'

// 创建Context
const MyContext = createContext();
// const {Provider} = MyContext;  // 类式子孙组件只需要Provider就可以使用，在this.context中拿到value
const {Provider, Consumer} = MyContext;  // 函数式子孙组件只能使用Consumer拿数据

class ContextDemo extends Component {
  state = {
    name: "Samuel"
  }

  render() {
    const {name} = this.state
    return (
      <div className="grand">
        <h2>这里是grandpa组件: name-{name}</h2>
        <Provider value={name}>
          <Father/>
        </Provider>
      </div>
    );
  }
}


class Father extends Component {
  render() {
    return (
      <div className="father">
        <h2>这里是father组件</h2>
        <Son/>
        <Son2/>
      </div>
    );
  }
}

/*
// 类组件
class Son extends Component {
  // 要声明接收context类型.
  static contextType = MyContext;

  render() {
    console.log('获取到grandpa的provider传递的数据:', this.context);
    return (
      <div className="son">
        <h2>这里是son组件: name--{this.context}</h2>
      </div>
    );
  }
}*/

// 函数式组件
function Son() {
  return (
    <div className="son">
      {/*函数式组件使用Consumer拿数据*/}
      <Consumer>
        {
          value => {
            return (<h2>这里是son组件: name--{value}</h2>)
          }
        }
      </Consumer>
    </div>
  )
}

function Son2() {
  const value = useContext(MyContext);
  return (
    <div>
      <p>son2组件使用useContext拿数据:{value}</p>
    </div>
  )
}


export default ContextDemo;
